
<template>
  <div class="edit-container">
    <van-cell-group>
      <van-cell v-for="(tag, index) in usertags" :key="index" class="tag-cell">
        <template #title>
          <div v-if="editIndex === index" class="edit-input">
            <van-field
                v-model="editedTag"
                placeholder="编辑标签"
                @blur="saveEditedTag"
                clearable
                class="tag-edit-field"
            />
          </div>
          <div v-else class="tag-text">
            {{ tag }}
          </div>
        </template>
        <template #value>
          <van-icon name="delete" class="delete-icon" @click="removeTag(index)"/>
          <van-icon name="edit" class="edit-icon" @click="editTag(index)"/>
        </template>
      </van-cell>
      <van-cell>
        <van-field v-model="newTag" placeholder="输入新的标签" class="add-tag-field"/>
      </van-cell>
    </van-cell-group>
    <van-button color="#ff7f50" @click="addTag" class="add-tag-button">添加标签</van-button>
    <van-button color="#7232dd" plain @click="saveTags" class="complete-button">完成</van-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import myAxios from "../plugins/myAxios.ts";
import { showToast, showFailToast } from 'vant';

const router = useRouter();
const route = useRoute();

// 响应式数据
const usertags = ref<string[]>([]);
const newTag = ref("");
const editIndex = ref<number | null>(null);
const editedTag = ref("");

// 初始化加载
onMounted(() => {
  const tagsQuery = route.query.tags;
  if (tagsQuery) {
    usertags.value = JSON.parse(tagsQuery as string);
  }
});

// 删除标签
const removeTag = async (index: number) => {
  const tagToRemove = usertags.value[index];
  try {
    const response = await updateUserTags("remove", tagToRemove, tagToRemove);
    if (response.status === 200) {
      usertags.value.splice(index, 1);
    }
  } catch (error) {
    console.error("删除失败:", error);
    showFailToast('删除失败，请重试');
  }
};

// 编辑标签
const editTag = (index: number) => {
  editIndex.value = index;
  editedTag.value = usertags.value[index];
};

// 添加标签（带格式验证）
const addTag = async () => {
  const newTagValue = newTag.value.trim();
  if (!newTagValue) return;
  if (!/^[\u4e00-\u9fa5a-zA-Z0-9]+$/.test(newTagValue)) {
    showFailToast('标签只能包含中文、字母和数字');
    return;
  }
  try {
    const response = await updateUserTags("add", newTagValue, newTagValue);
    if (response.status === 200) {
      usertags.value.push(newTagValue);
      newTag.value = "";
    }
  } catch (error) {
    console.error("添加失败:", error);
    showFailToast('添加失败，请重试');
  }
};

// 保存编辑（带防重复验证）
const saveEditedTag = async () => {
  if (editIndex.value === null || !editedTag.value.trim()) return;
  const newValue = editedTag.value.trim();
  if (usertags.value.includes(newValue)) {
    showFailToast('标签已存在');
    return;
  }
  try {
    const oldValue = usertags.value[editIndex.value];
    const response = await updateUserTags("update", oldValue, newValue);
    if (response.status === 200) {
      usertags.value[editIndex.value] = newValue;
      editIndex.value = null;
      editedTag.value = "";
    }
  } catch (error) {
    console.error("更新失败:", error);
    showFailToast('更新失败，请重试');
  }
};

// 统一API请求方法
const updateUserTags = async (operation: string, oldTag: string, newTag: string) => {
  try {
    const response = await myAxios.post("/user/updateTags", {
      operation,
      oldTag,
      newTag
    });
    return response.data;
  } catch (error) {
    console.error("API请求失败:", error);
    throw error;
  }
};

// 保存所有标签
const saveTags = async () => {
  try {
    const response = await myAxios.post("/user/updateTags", {
      operation: "save",
      tags: usertags.value
    });
    if (response.status === 200) {
      showToast('标签保存成功');
      router.push('/user/tags');
    }
  } catch (error) {
    console.error("保存失败:", error);
    showFailToast('保存失败，请重试');
  }
};
</script>

<style scoped>
/* 优化后的样式 */
.edit-container {
  padding: 16px;
}
.tag-cell {
  background-color: #f8f9fa;
  margin: 8px 0;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
}
.tag-cell:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.tag-text {
  font-size: 16px;
  color: #2c3e50;
  font-weight: 500;
}
.van-icon {
  transition: color 0.2s ease;
}
.delete-icon:hover {
  color: #ff4444;
}
.edit-icon:hover {
  color: #1989fa;
}
.add-tag-field {
  margin-top: 16px;
}
.add-tag-button {
  margin-top: 16px;
  border-radius: 24px;
}
.complete-button {
  margin-top: 8px;
  border-radius: 24px;
}
</style>
